<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
      :data="employees" - 绑定的数据[]
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框/忙等框
      @selection-change="selsChange" - 选项改变
      批量删除：type="selection - 选项
    -->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="30">
			</el-table-column>
			<el-table-column prop="username" label="用户" width="50" >
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="120" >
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="120" >
			</el-table-column>
			<el-table-column prop="salt" label="薪水" width="100">
			</el-table-column>
			<el-table-column prop="password" label="密码" width="180" >
			</el-table-column>
      <el-table-column prop="age" label="年龄" width="80" >
			</el-table-column>
      <el-table-column prop="state" label="状态" width="80" >
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">正常</span>
          <span style="color: red" v-else-if="scope.row.state==0">停用</span>
          <span style="color: darkslategray" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="部门ID" width="80" >
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>


		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :current-page="currentPage" :total="totals" style="float:right;">
      </el-pagination>
		</el-col>

		<!--编辑界面-->
    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email"></el-input>
        </el-form-item>
        <el-form-item label="盐值" prop="salt">
          <el-input v-model="saveForm.salt"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="saveForm.department_id" placeholder="请选择" clearable>
            <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工角色">
          <el-select v-model="saveForm.role_id" placeholder="请选择" clearable>
            <el-option
                v-for="item in roles"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
			  //1.分页相关数据
        employees: [],
        totals:0,
        pageSize:5,
        currentPage:1,
        listLoading: false,

        //2.高级查询所需数据
        keyword: '',//关键字查询


        title:'',
        saveFormVisible: false,
        saveLoading: false,
        saveFormRules: {
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入电话', trigger: 'blur' }
          ],
        },


        //3.编辑界面数据
        saveForm: {
          id:null,
          username: '',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age: '',
          state:1,
          department_id:null,
          role_id:null
        },

        //多条数据选中
				sels: [],//列表选中列

        departments:[],
        roles:[]
			}
		},
		methods: {
      //1.分页查询：获取部门列表
      getEmployees() {
        let para = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword:this.keyword
        };
        this.listLoading = true;

        this.$http.post("/employee",para).then((res) => {
          this.totals = res.data.totals;
          this.employees = res.data.data;
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error('系统繁忙，请稍后重试!!!');
        });
      },

      //2.点击某一页触发的方法
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getEmployees();
      },

      //3.关键字查询
      keywordQuery(){
        this.currentPage=1;
        this.getEmployees();
      },


      //4.显示新增界面
      handleAdd: function () {
        this.saveForm = {
          id:null,
          username: '',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age: '',
          state:1,
          department_id:null,
          role_id:null
        };
        this.title = " 增 加 ";
        this.saveFormVisible = true;
        this.getDepartments();
        this.getRoles();
      },


      //5.显示编辑界面
      handleEdit: function (index, row) {
        this.saveFormVisible = true;
        this.saveForm = Object.assign({}, row);
        this.title = " 修 改 ";
        this.getDepartments();
        this.getRoles();
      },

      //6.点击提交按钮添加或修改数据
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);
              this.$http.put("/employee",para).then(res=>{
                if (res.data.success){
                  this.$message.success("操作成功")
                  this.getEmployees()
                }else {
                  this.$message.error("系统繁忙，请稍后重试！【500】")
                }
                this.saveLoading=false
                this.saveFormVisible=false
              }).catch(res=>{
                this.$message.error("系统繁忙，请稍后重试！【400,404】")
              })
            });
          }
        });
      },


      //7.多条数据选中
      selsChange: function (sels) {
        this.sels = sels;
      },


      //8.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // let para = { ids: ids };
          this.$http.patch("/employee",ids).then(res=>{
            if (res.data.success){
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("操作成功")
              this.getEmployees()
            }else {
              this.$message.error("系统繁忙，请稍后重试！【500】")
            }
            this.saveLoading=false
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试！【400,404】")
          })
        }).catch(()=>{});
      },


			//删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '温馨提示', {
          type: 'warning'
        }).then(() => { //点击确认之后要执行的代码
          //显示加载框
          this.listLoading = true;
          //获取id
          var id= row.id;
          this.$http.delete("/employee/"+id).then(res=>{
            if (res.data.success){ //删除成功
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("删除成功") //3s自动消失
              this.getEmployees();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
            this.listLoading = false;//关闭加载框
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => { //点击取消之后要执行的代码
        });
      },

      getDepartments(){
        this.$http.get("/department").then(res => {
          //给员工经理们赋值
          this.departments = res.data;
        })
      },

      getRoles(){
        this.$http.get("/role").then(res => {
          this.roles = res.data;
        })
      }

		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>